import { BreadCrumbItemType } from '@/common-ui/braadcrumb/types/types'
import { RouteRecordRaw } from 'vue-router'
let firstMenu: any = null
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  // 1、先去加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('../router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    // console.log(key)
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  // 2、根据菜单获取需要添加的routes
  //   userMenus:
  // type ===1 =>children => type === 1
  // type ===2 => url -> route
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) {
          if (!firstMenu) {
            firstMenu = menu.url
          }
          routes.push(route)
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }
  _recurseGetRoute(userMenus)

  return routes
}
export { firstMenu }

// 面包屑
export function pathMapToMenu(
  userMenus: any[],
  path: string,
  breadCrumbList?: BreadCrumbItemType[]
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const firstMenu = pathMapToMenu(menu.children ?? [], path)
      if (firstMenu) {
        breadCrumbList?.push(menu)
        breadCrumbList?.push(firstMenu)
        return firstMenu
      }
    } else if (menu.type === 2 && menu.url === path) {
      return menu
    }
  }
}
export function breadCrumbMapToMenu(
  userMenus: any[],
  path: string
): BreadCrumbItemType[] {
  const breadCrumbList: BreadCrumbItemType[] = []
  pathMapToMenu(userMenus, path, breadCrumbList)
  return breadCrumbList
}
